package com.example.musicaiap.ui.playlist

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.viewModelScope
import com.example.musicaiap.data.repository.MusicRepository
import com.example.musicaiap.domain.model.Song
import com.example.musicaiap.mvi.base.MviViewModel
import com.example.musicaiap.service.MediaBrowserHelper
import com.example.musicaiap.service.PlaybackState
import com.example.musicaiap.ui.player.PlayerController
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * 播放列表的ViewModel
 */
@HiltViewModel
class PlaylistViewModel @Inject constructor(
    private val musicRepository: MusicRepository,
    private val playerController: PlayerController,
    private val mediaBrowserHelper: MediaBrowserHelper,
    savedStateHandle: SavedStateHandle
) : MviViewModel<PlaylistContract.State, PlaylistContract.Intent, PlaylistContract.Effect>() {
    
    private val playlistId: String = checkNotNull(savedStateHandle["playlistId"])
    
    // 暴露播放状态以供UI层访问
    val playbackState: StateFlow<PlaybackState> = mediaBrowserHelper.playbackState
    
    override fun createInitialState(): PlaylistContract.State {
        return PlaylistContract.State(isLoading = true)
    }
    
    init {
        loadPlaylist(playlistId)
        observePlayerState()
    }
    
    override fun handleIntent(intent: PlaylistContract.Intent) {
        when (intent) {
            is PlaylistContract.Intent.LoadPlaylist -> loadPlaylist(intent.playlistId)
            is PlaylistContract.Intent.ClickSong -> handleSongClick(intent.song)
            is PlaylistContract.Intent.TogglePlayPause -> togglePlayPause()
            is PlaylistContract.Intent.PlayAll -> playAllSongs()
            is PlaylistContract.Intent.NextSong -> playNextSong()
            is PlaylistContract.Intent.PreviousSong -> playPreviousSong()
            is PlaylistContract.Intent.ToggleFavorite -> toggleFavorite()
            is PlaylistContract.Intent.BackClick -> navigateBack()
            is PlaylistContract.Intent.ClickMiniPlayer -> navigateToPlayer()
            is PlaylistContract.Intent.SeekTo -> seekTo(intent.position)
        }
    }
    
    private fun loadPlaylist(playlistId: String) {
        viewModelScope.launch {
            setState { copy(isLoading = true, error = null) }
            
            try {
                // 并行加载数据
                val playlistDeferred = async { musicRepository.getPlaylist(playlistId) }
                val songsDeferred = async { musicRepository.getPlaylistSongs(playlistId) }
                
                val playlist = playlistDeferred.await()
                val songs = songsDeferred.await()
                
                setState {
                    copy(
                        isLoading = false,
                        playlist = playlist,
                        songs = songs
                    )
                }
            } catch (e: Exception) {
                setState {
                    copy(
                        isLoading = false,
                        error = "加载播放列表失败: ${e.localizedMessage}"
                    )
                }
            }
        }
    }
    
    private fun handleSongClick(song: Song) {
        viewModelScope.launch {
            playerController.play(song)
//            sendEffect(PlaylistContract.Effect.ShowToast("正在播放: ${song.title}"))
        }
    }
    
    private fun togglePlayPause() {
        viewModelScope.launch {
            if (currentState.isPlaying) {
                playerController.pause()
            } else {
                playerController.resume()
            }
        }
    }
    
    private fun playAllSongs() {
        viewModelScope.launch {
            val songs = currentState.songs
            if (songs.isNotEmpty()) {
                playerController.play(songs)
                sendEffect(PlaylistContract.Effect.ShowToast("播放全部"))
            }
        }
    }
    
    private fun playNextSong() {
        viewModelScope.launch {
            playerController.skipToNext()
        }
    }
    
    private fun playPreviousSong() {
        viewModelScope.launch {
            playerController.skipToPrevious()
        }
    }
    
    private fun toggleFavorite() {
        viewModelScope.launch {
            val currentSong = playerController.playerState.value.currentSong
            currentSong?.let { song ->
                playerController.toggleFavorite(song.id)
                
                // 反馈会从PlayerController的副作用中处理
            }
        }
    }
    
    private fun navigateBack() {
        viewModelScope.launch {
            sendEffect(PlaylistContract.Effect.NavigateBack)
        }
    }
    
    private fun navigateToPlayer() {
        viewModelScope.launch {
            sendEffect(PlaylistContract.Effect.NavigateToPlayer)
        }
    }
    
    private fun observePlayerState() {
        viewModelScope.launch {
            playerController.playerState.collectLatest { playerState ->
                setState {
                    copy(
                        currentPlayingSong = playerState.currentSong,
                        isPlaying = playerState.isPlaying,
                        currentPosition = playerState.currentPosition,
                        duration = playerState.duration,
                        isFavorite = playerState.isFavorite
                    )
                }
            }
        }
    }

    /**
     * 跳转到指定播放位置
     */
    private fun seekTo(position: Long) {
        viewModelScope.launch {
            playerController.seekTo(position)
        }
    }

    /**
     * 处理用户意图的公共方法，供外部调用
     */
    fun processIntent(intent: PlaylistContract.Intent) {
        handleIntent(intent)
    }
} 